package com.mashangwan.paleto.common;

import com.mashangwan.paleto.domain.User;
import com.mashangwan.paleto.security.model.UserContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * com.seelyn.superp.core.common
 *
 * @author linfeng
 * @since 2017/7/30
 */
public class UserUtils {

    public static final String SESSION_USER_KEY = "SUPERP_SESSION_USER_KEY";
    public static final String CURRENT_DUTIES_ID = "curentDutiesId";

    /**
     * 获取当期用户
     *
     * @return 用户
     */
    public static User getUser(HttpServletRequest request, HttpServletResponse response) {

        SecurityContextImpl securityContext = (SecurityContextImpl) SecurityContextHolder.getContext();
        Authentication auth = securityContext.getAuthentication();
        UserContext principal = (UserContext) auth.getPrincipal();
        User user;
        if (principal != null) {
            user = principal.getUser();
        } else {
            user = new User();
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return user;

    }

    public static User getCurrentUser() {
        UserContext principal = getUserContext();
        return principal != null ? principal.getUser() : null;
    }



    private static UserContext getUserContext() {
        return (UserContext) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }


    /**
     * 获取缓存对象
     *
     * @param key 缓存key
     * @return 缓存对象
     */
    public static Object getCache(String key) {
        return getCache(key, null);
    }

    public static Object getCache(String key, Object defaultValue) {
        Object obj = getCacheMap().get(key);
        return obj == null ? defaultValue : obj;
    }

    public static Map<String, Object> getCacheMap() {
        Map<String, Object> map = new HashMap<>();
        UserContext principal = getUserContext();
        return principal != null ? principal.getCacheMap() : map;
    }

}
